<template>
  <div class="editorBox">
    <div class="infoBox">
      <el-form class="simpleInfoBox" :model="blog" :rules="rules" ref="ruleForm" >
        <div class="remind">文章标题</div>
        <el-form-item prop="title">
          <el-input
            type="textarea"
            :autosize="{ minRows: 1,maxRows: 2}"
            placeholder="请输入标题"
            maxlength="50"
            show-word-limit
            v-model="blog.title">
          </el-input>
        </el-form-item>

        <el-form-item prop="intro">
          <div class="remind">简介</div>
          <el-input
            type="textarea"
            :autosize="{ minRows: 4,maxRows: 4}"
            placeholder="请输入简介"
            maxlength="100"
            show-word-limit
            v-model="blog.intro"  style="box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)">
          </el-input>
        </el-form-item>
      </el-form>

      <div class="uploadImgBox">
        <div class="remind">封面图片</div>
        <el-upload
          ref="elUpload"
          class="upload-demo"
          drag
          action="#"
          :auto-upload="false"
          :limit="1"
          :on-change="onchangeImg"
          :before-upload="beforeAvatarUpload"
          :on-success="coverUploadReturnInfo">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </div>
    </div>


    <div class="remind">正文</div>
    <mavon-editor ref=md @imgAdd="$imgAdd" @imgDel="$imgDel" v-model="blog.md"></mavon-editor>

    <div style="margin: 50px auto;display: block;width: 100%">
      <el-button type="info"  @click="back">&lt;&lt;返回主页</el-button>
      <el-button type="info"  @click="submit">提 交</el-button>
    </div>
    <div style="margin-top: 50px;height: 1px"></div>
  </div>
</template>

<script>
import axios from "axios";
export default {
  name: "Editor",
  data(){
    return{
      blog: {
        title: "",
        intro: "",
        coverUrl: "",
        uid: 0,
        md:"",
      },
      myParam: new FormData(),
      canSubmit: false,
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        intro: [
          { required: true, message: '请输入简介', trigger: 'blur' }
        ]
      },
    }
  },

  methods:{
    coverUploadReturnInfo(res){
      console.log(res)
    },
    onchangeImg(file,fileList){
      const isLt2M = file.size / 1024 / 1024 < 2
      let endType = file.name.substring(file.name.lastIndexOf('.') + 1)
      let isJPG = (endType.toLowerCase()=="jpg")
      let isPng = (endType.toLowerCase()=="png")
      if (!isJPG&&!isPng) {
        this.$message.error('上传头像图片只能是 JPG, PNG 格式!')
        this.$refs['elUpload'].clearFiles();
        this.canSubmit=false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        this.$refs['elUpload'].clearFiles();
        this.canSubmit=false
      }
      this.canSubmit=true
      this.myParam.append("myFile",fileList[0].raw)
    },
    beforeAvatarUpload (file) {
      return true;
    },
    // 绑定@imgAdd event
    $imgAdd(pos, $file){
      // 第一步.将图片上传到服务器.
      let formData = new FormData();
      formData.append('image', $file);
      axios({
        url: '/upload',
        method: 'post',
        data: formData,
        headers: { 'Content-Type': 'multipart/form-data' },
      }).then((url) => {
        // 第二步.将返回的url替换到文本原位置![...](./0) -> ![...](url)
        /**
         * $vm 指为mavonEditor实例，可以通过如下两种方式获取
         * 1. 通过引入对象获取: `import {mavonEditor} from ...` 等方式引入后，`$vm`为`mavonEditor`
         * 2. 通过$refs获取: html声明ref : `<mavon-editor ref=md ></mavon-editor>，`$vm`为 `this.$refs.md`
         */
        this.$refs.md.$img2Url(pos, url.data);
      })
    },
    $imgDel($file){
      let url = "/www/wwwroot/www.enwayouli.top/dist/" + $file[0].substring(26)
      axios.get("remove?imgUrl="+url).then(res => {
        console.log(res.data)
      })
    },
    back(){
      this.$router.push("/index")
    },
    submit: function () {
      let admin = JSON.parse(window.localStorage.getItem("access-admin"))
      if (admin.uid!=1){
        this.$message.error("权限不足")
        return false;
      }
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      };
      if(this.blog.md.trim() == ""){
        this.$message.error("请输入正文")
        return false;
      }
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          if (this.canSubmit) {
            //防止用户快速重复点击
            this.canSubmit = false;
            this.myParam.append("title", this.blog.title)
            this.myParam.append("intro", this.blog.intro)
            this.myParam.append("md", this.blog.md)
            this.myParam.append("uid", JSON.parse(window.localStorage.getItem("access-admin")).uid)
            this.$axios.post("/blogUpload", this.myParam, config).then(res => {
              if (res.data){
                this.$message.info("上传成功！")
                this.$router.push("/index")
              } else {
                this.$message.error("上传失败！")
                location.reload();
              }
            })
            this.myParam = new FormData();
            this.$refs['elUpload'].clearFiles();
          } else {
            this.$message.error("请上传一张封面图！")
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },
  }
}
</script>

<style scoped>
.editorBox{
  width: 1200px;
  margin: 0 auto;
}
.remind{
  color: #606266;
  font-size: 14px;
  height: 50px;
  line-height: 70px;
}
.infoBox{
  width: 100%;
  display: flex;
}
.simpleInfoBox{
  margin-right: 50px;
  flex: 7;
}
.uploadImgBox{
  flex: 3;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
